
import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import './index.scss'
import until from '../../untils/lyUntils'


class Index extends Component {
	static defaultProps = {
		index: 0,
		titles: ['商品详情', '评论'],
		onTabChange: () => { },
		txtColor: '#f00'
	}
	constructor() {
		super(...arguments)
	}
	state = {
		w: 0,
		tabsHrW: 0,
		leftPlace: 0,
		nowIndex: 0
	}

	componentDidShow() {
		until.getDomInfo('.ly-tabs', this.$scope).then((res) => {
			this.setState({
				w: res.width,
				tabsHrW: res.width,
				nowIndex: this.props.index
			}, () => {
				this.setHrPlace()
			})
		})
	}
	componentDidHide() { }


	setHrPlace() {
		const { w, nowIndex } = this.state;
		const { titles } = this.props;
		this.setState({
			leftPlace: nowIndex * w
		}, () => {
			this.props.onTabChange(nowIndex, titles[nowIndex])
		})
	}
	changeTabs(i) {
		this.setState({
			nowIndex: i
		}, () => {
			this.setHrPlace()
		})
	}

	render() {
		const { tabsHrW, leftPlace, nowIndex } = this.state;
		const { titles, txtColor } = this.props;
		return (
			<View className='tabsBox' style={{ borderColor: txtColor }}>
				{
					titles.map((val, i) => (
						<View className='ly-tabs' style={{ color: nowIndex == i ? txtColor : '' }} onClick={this.changeTabs.bind(this, i)} key={'tab' + i}>{val}</View>
					))
				}
				<View className='tabsHr' style={{ width: tabsHrW + 'px', left: leftPlace + 'px', backgroundColor: txtColor }}></View>
			</View >
		)
	}
}
export default Index;